package com.nmgsr.ptmsapp.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.ExifInterface;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.util.Size;
import android.util.SizeF;
import android.view.OrientationEventListener;
import android.view.ScaleGestureDetector;
import android.view.Surface;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraControl;
import androidx.camera.core.CameraInfo;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.common.util.concurrent.ListenableFuture;
import com.nmgsr.nettools.util.ToastUtil;
import com.nmgsr.ptmsapp.R;
import com.nmgsr.ptmsapp.utils.UsbReaderTool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

public class SingleCameraActivity extends AppCompatActivity {
    public enum CameraRotationMode {
        ROTATION_AUTO,
        ROTATION_HORIZONTAL,
        ROTATION_VERTICAL,
        ROTATION_0,
        ROTATION_90,
        ROTATION_180,
        ROTATION_270
    }

    public enum CameraSizeMode {
        SIZE_1080_1920,
        SIZE_768_1024,
        SIZE_864_864,
        SIZE_960_960
    }

    public static class Builder {
        private final Context context;
        private final Intent intent;

        public Builder(Context context) {
            this.context = context;
            this.intent = new Intent(context, SingleCameraActivity.class);
        }

        public Builder setSizeMode(CameraSizeMode cameraSizeMode) {
            intent.putExtra(EXTRA_SIZE_MODE, cameraSizeMode.name());
            return this;
        }

        public Builder setRotationMode(CameraRotationMode cameraRotationMode) {
            intent.putExtra(EXTRA_ROTATION_MODE, cameraRotationMode.name());
            return this;
        }

        public Builder setAction(String action) {
            intent.setAction(action);
            return this;
        }

        public Intent build() {
            return intent;
        }
    }

    private static final String TAG = "SingleCameraActivity";
    private static final int REQUEST_CODE_PERMISSIONS = 101;
    private final String[] REQUIRED_PERMISSIONS = new String[]{Manifest.permission.CAMERA};
    public static final String EXTRA_ROTATION_MODE = "rotationMode";
    public static final String EXTRA_SIZE_MODE = "sizeMode";
    private static boolean flashlightOpen = false; // 闪光灯全局开关，默认关
    private static boolean isFrontCamera = false;
    private CameraRotationMode cameraRotationMode = CameraRotationMode.ROTATION_HORIZONTAL;
    private CameraSizeMode cameraSizeMode = CameraSizeMode.SIZE_1080_1920;
    private String action;

    private Preview preview;
    private CameraSelector cameraSelector;
    private ImageCapture imageCapture;
    private CameraControl cameraControl;
    private CameraInfo cameraInfo;
    private OrientationEventListener orientationEventListener;
    private ScaleGestureDetector scaleGestureDetector;

    private PreviewView pvCameraPreview;
    private CardView cvCapture;
    private ImageView imClose, imCameraDirectionReminder, imFlashlightSwitch, imgLoopCameraSelect;
    private ProcessCameraProvider cameraProvider;

    private TextView textView;
    private UsbReaderTool usbReaderTool;
    public static Intent newIntent(Context context, CameraRotationMode cameraRotationMode) {
        Intent intent = new Intent(context, SingleCameraActivity.class);
        intent.putExtra(EXTRA_ROTATION_MODE, cameraRotationMode.name());
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_single_camera);

        pvCameraPreview = findViewById(R.id.pv_camera_preview);
        cvCapture = findViewById(R.id.cv_take_pictures);
        imClose = findViewById(R.id.im_close);
        //imCameraDirectionReminder = findViewById(R.id.im_camera_direction_reminder);
        //imCameraDirectionReminder.setVisibility(View.GONE); // 先隐藏角度指示器，在相机启动后再显示角度指示器
        imFlashlightSwitch = findViewById(R.id.im_flashlight_switch);
        imFlashlightSwitch.setVisibility(View.GONE);
        imgLoopCameraSelect = findViewById(R.id.img_loop_camera_select);
        textView = findViewById(R.id.textView);
        usbReaderTool = new UsbReaderTool(this, textView);
        String rotationModeName = getIntent().getStringExtra("rotationMode");
        if (rotationModeName != null) {
            cameraRotationMode = CameraRotationMode.valueOf(rotationModeName);
        }
        String sizeModeName = getIntent().getStringExtra("sizeMode");
        if (sizeModeName != null) {
            cameraSizeMode = CameraSizeMode.valueOf(sizeModeName);
        }
        action = getIntent().getAction();

        // 检查并请求权限
        if (allPermissionsGranted()) {
            startCamera();
        } else {
            ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
        }

        imClose.setOnClickListener(v -> finish());
        cvCapture.setOnClickListener(v -> {
            if (!allPermissionsGranted()) {
                ToastUtil.showToast("未获取相机权限");
                return;
            }
            takePhoto();
        });
        imFlashlightSwitch.setOnClickListener(v -> {
            if (!allPermissionsGranted()) {
                ToastUtil.showToast("未获取相机权限");
                return;
            }
            if (imageCapture == null) return;
            flashlightOpen = !flashlightOpen;
            imageCapture.setFlashMode(flashlightOpen ? ImageCapture.FLASH_MODE_ON : ImageCapture.FLASH_MODE_OFF);
            imFlashlightSwitch.setImageDrawable(flashlightOpen ? getDrawable(R.drawable.ic_flashlight_open_gray) : getDrawable(R.drawable.ic_flashlight_close_gray));
        });
        imgLoopCameraSelect.setOnClickListener(v -> {
            if (!allPermissionsGranted()) {
                ToastUtil.showToast("未获取相机权限");
                return;
            }
            isFrontCamera = !isFrontCamera;
            startCamera();
        });

        setupPinchToZoom(); // 开启手势缩放
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            if (allPermissionsGranted()) {
                startCamera();
            } else {
                ToastUtil.showToast("未获取相机权限");
            }
        }
    }

    private boolean allPermissionsGranted() {
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private void startCamera() {
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        cameraProviderFuture.addListener(() -> {
            try {
                cameraProvider= cameraProviderFuture.get();

                // 解绑之前的用例
                cameraProvider.unbindAll();

                // 获取设备支持的所有分辨率
//                List<CameraInfo> availableCameraInfos = cameraProvider.getAvailableCameraInfos();
//                if (availableCameraInfos.isEmpty()) {
//                    Log.e(TAG, "No cameras available");
//                    return;
//                }

                //cameraInfo = availableCameraInfos.get(0);
                CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
                String cameraId = null;

                for (String id : cameraManager.getCameraIdList()) {
                    CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(id);
                    Integer lensFacing = characteristics.get(CameraCharacteristics.LENS_FACING);
                    if ((isFrontCamera && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_FRONT) ||
                            (!isFrontCamera && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK)) {
                        cameraId = id;
                        break;
                    }
                }

                if (cameraId == null) {
                    Log.e(TAG, "Failed to find camera ID");
                    return;
                }

                CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
                StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

                if (map == null) {
                    Log.e(TAG, "StreamConfigurationMap is null");
                    return;
                }

                Size[] supportedSizes = map.getOutputSizes(ImageFormat.JPEG);
                Size targetSize = switch (cameraSizeMode) {
                    case SIZE_768_1024 -> new Size(768, 1024);
                    case SIZE_864_864 -> new Size(864, 864);
                    case SIZE_960_960 -> new Size(960, 960);
                    default -> new Size(1080, 1920);
                };

                Size closestSize = getClosestSupportedSize(supportedSizes, targetSize);
                if (closestSize == null) {
                    Log.e(TAG, "No supported size found");
                    return;
                }

                Log.d(TAG, "on size: " + closestSize.getWidth() + "x" + closestSize.getHeight());
                if (closestSize.getWidth()<1080 && closestSize.getHeight()<1920){
                    closestSize = new Size(1920, 1080);
                }else if(closestSize.getWidth()>=1080 || closestSize.getHeight()>=1920){
                    closestSize = new Size(1080, 1920);
                }
                Log.d(TAG, "Selected size: " + closestSize.getWidth() + "x" + closestSize.getHeight());
                preview = new Preview.Builder()
                        .setTargetResolution(closestSize)
                        .build();
                preview.setSurfaceProvider(pvCameraPreview.getSurfaceProvider());

                imageCapture = new ImageCapture.Builder()
                        .setTargetResolution(closestSize)
                        .build();
                // 打印支持的分辨率
                // printSupportedResolutions();
                // 默认选择后置摄像头
                cameraSelector = new CameraSelector.Builder()
                        .requireLensFacing(isFrontCamera ? CameraSelector.LENS_FACING_FRONT : CameraSelector.LENS_FACING_BACK)
                        .build();

                // 绑定到生命周期
                Camera camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture);
                cameraControl = camera.getCameraControl();
                cameraInfo = camera.getCameraInfo();

                switch (cameraRotationMode) {
                    case ROTATION_0:
                        imageCapture.setTargetRotation(Surface.ROTATION_0);
                        imCameraDirectionReminder.setRotation(0);
                        imFlashlightSwitch.setRotation(0);
                        break;
                    case ROTATION_90:
                        imageCapture.setTargetRotation(Surface.ROTATION_90);
                        imCameraDirectionReminder.setRotation(90);
                        imFlashlightSwitch.setRotation(90);
                        break;
                    case ROTATION_180:
                        imageCapture.setTargetRotation(Surface.ROTATION_180);
                        imCameraDirectionReminder.setRotation(180);
                        imFlashlightSwitch.setRotation(180);
                        break;
                    case ROTATION_270:
                        imageCapture.setTargetRotation(Surface.ROTATION_270);
                        imCameraDirectionReminder.setRotation(270);
                        imFlashlightSwitch.setRotation(270);
                        break;
                    case ROTATION_VERTICAL:
                        // 首次进入相机默认角度
                        imageCapture.setTargetRotation(Surface.ROTATION_0);
                        imCameraDirectionReminder.setRotation(0);
                        imFlashlightSwitch.setRotation(0);

                        orientationEventListener = new OrientationEventListener(this) {
                            @Override
                            public void onOrientationChanged(int orientation) {
                                int rotation;
                                if (orientation >= 90 && orientation < 270) {
                                    rotation = Surface.ROTATION_180;
                                    imCameraDirectionReminder.setRotation(180);
                                    imFlashlightSwitch.setRotation(180);
                                } else {
                                    rotation = Surface.ROTATION_0;
                                    imCameraDirectionReminder.setRotation(0);
                                    imFlashlightSwitch.setRotation(0);
                                }

                                imageCapture.setTargetRotation(rotation);
                            }
                        };
                        orientationEventListener.enable();
                        break;
                    case ROTATION_HORIZONTAL:
                        imageCapture.setTargetRotation(Surface.ROTATION_90);
                        imCameraDirectionReminder.setRotation(90);
                        imFlashlightSwitch.setRotation(90);
                        orientationEventListener = new OrientationEventListener(this) {
                            @Override
                            public void onOrientationChanged(int orientation) {
                                int rotation;
                                if (orientation >= 0 && orientation < 180) {
                                    rotation = Surface.ROTATION_270;
                                    imCameraDirectionReminder.setRotation(270);
                                    imFlashlightSwitch.setRotation(270);
                                } else {
                                    rotation = Surface.ROTATION_90;
                                    imCameraDirectionReminder.setRotation(90);
                                    imFlashlightSwitch.setRotation(90);
                                }

                                imageCapture.setTargetRotation(rotation);
                            }
                        };

                        orientationEventListener.enable();
                        break;
                    default:
                        imageCapture.setTargetRotation(Surface.ROTATION_0);
                        imCameraDirectionReminder.setRotation(0);
                        imFlashlightSwitch.setRotation(0);
                        orientationEventListener = new OrientationEventListener(this) {
                            @Override
                            public void onOrientationChanged(int orientation) {
                                int rotation;
                                if (orientation >= 45 && orientation < 135) {
                                    rotation = Surface.ROTATION_270;
                                    imCameraDirectionReminder.setRotation(270);
                                    imFlashlightSwitch.setRotation(270);
                                } else if (orientation >= 135 && orientation < 225) {
                                    rotation = Surface.ROTATION_180;
                                    imCameraDirectionReminder.setRotation(180);
                                    imFlashlightSwitch.setRotation(180);
                                } else if (orientation >= 225 && orientation < 315) {
                                    rotation = Surface.ROTATION_90;
                                    imCameraDirectionReminder.setRotation(90);
                                    imFlashlightSwitch.setRotation(90);
                                } else {
                                    rotation = Surface.ROTATION_0;
                                    imCameraDirectionReminder.setRotation(0);
                                    imFlashlightSwitch.setRotation(0);
                                }

                                imageCapture.setTargetRotation(rotation);
                            }
                        };
                        orientationEventListener.enable();
                }

                if (flashlightOpen) { // 初始化闪光灯开关，View层默认关闭闪光灯，若用户之前设置开关为开时载入闪光灯开
                    imageCapture.setFlashMode(ImageCapture.FLASH_MODE_ON);
                    imFlashlightSwitch.setImageDrawable(getDrawable(R.drawable.ic_flashlight_open_gray));
                }
                imCameraDirectionReminder.setVisibility(View.GONE);
                imFlashlightSwitch.setVisibility(View.VISIBLE);

            } catch (Exception e) {
                Log.e(TAG, "Use case binding failed", e);
            }
        }, ContextCompat.getMainExecutor(this));
    }

    private Size getClosestSupportedSize(Size[] supportedSizes, Size targetSize) {
        if (supportedSizes == null || supportedSizes.length == 0) {
            return null;
        }

        Size closestSize = null;
        int minDiff = Integer.MAX_VALUE;

        for (Size size : supportedSizes) {
            int diff = Math.abs(size.getWidth() - targetSize.getWidth()) + Math.abs(size.getHeight() - targetSize.getHeight());
            if (diff < minDiff) {
                minDiff = diff;
                closestSize = size;
            }
        }

        return closestSize;
    }
    private void printSupportedResolutions() {
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        cameraProviderFuture.addListener(() -> {
            try {
                cameraProvider = cameraProviderFuture.get();
                CameraSelector cameraSelector = new CameraSelector.Builder()
                        .requireLensFacing(isFrontCamera ? CameraSelector.LENS_FACING_FRONT : CameraSelector.LENS_FACING_BACK)
                        .build();

                // 获取可用的相机信息列表
                List<CameraInfo> availableCameraInfos = cameraProvider.getAvailableCameraInfos();
                if (availableCameraInfos.isEmpty()) {
                    Log.e(TAG, "No cameras available");
                    return;
                }

                // 获取第一个相机的信息
                CameraInfo cameraInfo = availableCameraInfos.get(0);

                // 使用 CameraManager 来获取相机特性
                CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
                String cameraId = null;

                for (String id : cameraManager.getCameraIdList()) {
                    CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(id);
                    Integer lensFacing = characteristics.get(CameraCharacteristics.LENS_FACING);
                    if ((isFrontCamera && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_FRONT) ||
                            (!isFrontCamera && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK)) {
                        cameraId = id;
                        break;
                    }
                }

                if (cameraId == null) {
                    Log.e(TAG, "Failed to find camera ID");
                    return;
                }

                CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
                StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

                if (map != null) {
                    Size[] outputSizes = map.getOutputSizes(ImageFormat.JPEG);
                    Log.d(TAG, "Supported JPEG resolutions:");
                    for (Size size : outputSizes) {
                        Log.d(TAG, size.getWidth() + "x" + size.getHeight());
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "Error getting camera characteristics", e);
            }
        }, ContextCompat.getMainExecutor(this));
    }
    private void startCamera16() {
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        cameraProviderFuture.addListener(() -> {
            try {
                cameraProvider = cameraProviderFuture.get();

                // 解绑之前的用例
                cameraProvider.unbindAll();

                CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
                String cameraId = null;

                for (String id : cameraManager.getCameraIdList()) {
                    CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(id);
                    Integer lensFacing = characteristics.get(CameraCharacteristics.LENS_FACING);
                    if ((isFrontCamera && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_FRONT) ||
                            (!isFrontCamera && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK)) {
                        cameraId = id;
                        break;
                    }
                }

                if (cameraId == null) {
                    Log.e(TAG, "Failed to find camera ID");
                    return;
                }

                CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
                StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

                if (map == null) {
                    Log.e(TAG, "StreamConfigurationMap is null");
                    return;
                }

                Size[] supportedSizes = map.getOutputSizes(ImageFormat.JPEG);
                Size targetSize = new Size(1080, 1920); // 16:9 比例

                Size closestSize = getClosestSupportedSize16(supportedSizes, targetSize);
                if (closestSize == null) {
                    Log.e(TAG, "No supported size found");
                    return;
                }

                Log.d(TAG, "Selected size: " + closestSize.getWidth() + "x" + closestSize.getHeight());
                preview = new Preview.Builder()
                        .setTargetResolution(closestSize)
                        .build();
                preview.setSurfaceProvider(pvCameraPreview.getSurfaceProvider());

                imageCapture = new ImageCapture.Builder()
                        .setTargetResolution(closestSize)
                        .build();

                cameraSelector = new CameraSelector.Builder()
                        .requireLensFacing(isFrontCamera ? CameraSelector.LENS_FACING_FRONT : CameraSelector.LENS_FACING_BACK)
                        .build();

                Camera camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture);
                cameraControl = camera.getCameraControl();
                cameraInfo = camera.getCameraInfo();

                // 初始化 OrientationEventListener
                orientationEventListener = new OrientationEventListener(this) {
                    @Override
                    public void onOrientationChanged(int orientation) {
                        int rotation;
                        if (orientation >= 315 || orientation < 45) {
                            rotation = Surface.ROTATION_0;
                        } else if (orientation >= 45 && orientation < 135) {
                            rotation = Surface.ROTATION_90;
                        } else if (orientation >= 135 && orientation < 225) {
                            rotation = Surface.ROTATION_180;
                        } else {
                            rotation = Surface.ROTATION_270;
                        }

                        imageCapture.setTargetRotation(rotation);
                    }
                };

                // 启用 OrientationEventListener
                orientationEventListener.enable();

                switch (cameraRotationMode) {
                    case ROTATION_0:
                        imageCapture.setTargetRotation(Surface.ROTATION_0);
                        imCameraDirectionReminder.setRotation(0);
                        imFlashlightSwitch.setRotation(0);
                        break;
                    case ROTATION_90:
                        imageCapture.setTargetRotation(Surface.ROTATION_90);
                        imCameraDirectionReminder.setRotation(90);
                        imFlashlightSwitch.setRotation(90);
                        break;
                    case ROTATION_180:
                        imageCapture.setTargetRotation(Surface.ROTATION_180);
                        imCameraDirectionReminder.setRotation(180);
                        imFlashlightSwitch.setRotation(180);
                        break;
                    case ROTATION_270:
                        imageCapture.setTargetRotation(Surface.ROTATION_270);
                        imCameraDirectionReminder.setRotation(270);
                        imFlashlightSwitch.setRotation(270);
                        break;
                    case ROTATION_VERTICAL:
                        // 首次进入相机默认角度
                        imageCapture.setTargetRotation(Surface.ROTATION_0);
                        imCameraDirectionReminder.setRotation(0);
                        imFlashlightSwitch.setRotation(0);
                        break;
                    case ROTATION_HORIZONTAL:
                        imageCapture.setTargetRotation(Surface.ROTATION_90);
                        imCameraDirectionReminder.setRotation(90);
                        imFlashlightSwitch.setRotation(90);
                        break;
                    default:
                        imageCapture.setTargetRotation(Surface.ROTATION_0);
                        imCameraDirectionReminder.setRotation(0);
                        imFlashlightSwitch.setRotation(0);
                }

                if (flashlightOpen) {
                    imageCapture.setFlashMode(ImageCapture.FLASH_MODE_ON);
                    imFlashlightSwitch.setImageDrawable(getDrawable(R.drawable.ic_flashlight_open_gray));
                }
                imCameraDirectionReminder.setVisibility(View.GONE);
                imFlashlightSwitch.setVisibility(View.VISIBLE);

            } catch (Exception e) {
                Log.e(TAG, "Use case binding failed", e);
            }
        }, ContextCompat.getMainExecutor(this));
    }


    private Size getClosestSupportedSize16(Size[] supportedSizes, Size targetSize) {
        if (supportedSizes == null || supportedSizes.length == 0) {
            return null;
        }

        Size closestSize = null;
        int minDiff = Integer.MAX_VALUE;

        for (Size size : supportedSizes) {
            // 检查是否为 16:9 比例
            if (size.getWidth() * 16 == size.getHeight() * 9) {
                int diff = Math.abs(size.getWidth() - targetSize.getWidth()) + Math.abs(size.getHeight() - targetSize.getHeight());
                if (diff < minDiff) {
                    minDiff = diff;
                    closestSize = size;
                }
            }
        }

        // 如果没有找到 16:9 比例的分辨率，则选择最接近的分辨率
        if (closestSize == null) {
            for (Size size : supportedSizes) {
                int diff = Math.abs(size.getWidth() - targetSize.getWidth()) + Math.abs(size.getHeight() - targetSize.getHeight());
                if (diff < minDiff) {
                    minDiff = diff;
                    closestSize = size;
                }
            }
        }

        return closestSize;
    }
    private void takePhoto() {
        if (imageCapture == null) return;

        // 创建 "Single Camera" 文件夹路径
        File singleCameraDir = new File(getExternalFilesDir(null), "SingleCameraPicture");
        if (!singleCameraDir.exists()) {
            boolean isCreated = singleCameraDir.mkdirs();
            if (!isCreated) {
                Log.e(TAG, "Failed to create directory: " + singleCameraDir.getAbsolutePath());
                return;
            }
        }

        // 创建文件名和完整路径
        File photoFile = new File(singleCameraDir, new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS", Locale.CHINA).format(System.currentTimeMillis()) + ".jpg");

        // 配置保存选项
        ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(photoFile).build();

        // 拍照并保存到指定路径
        imageCapture.takePicture(outputFileOptions, ContextCompat.getMainExecutor(this), new ImageCapture.OnImageSavedCallback() {
            @Override
            public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                // 图片保存成功
                compressImage(photoFile); // 调用压缩方法
                saveFocalLengthToExif(photoFile); // 保存焦距信息到 EXIF
                String photoPath = photoFile.getAbsolutePath();
                Intent cameraIntent = new Intent();
                if (action != null) {
                    cameraIntent.setAction(action);
                }
                cameraIntent.putExtra("photoPath", photoPath);
                setResult(RESULT_OK, cameraIntent);
                finish();
            }

            @Override
            public void onError(@NonNull ImageCaptureException exception) {
                Log.e(TAG, "Photo capture failed: " + exception.getMessage(), exception);
            }
        });
    }
    private void saveFocalLengthToExif(File file) {
        try {
            ExifInterface exifInterface = new ExifInterface(file.getAbsolutePath());

            // 获取焦距信息
            float focalLength = getFocalLength();
            String sensorSize = getSensorSize();
            Log.e("焦距", String.valueOf(focalLength));
            // 设置焦距信息到 EXIF
            exifInterface.setAttribute(ExifInterface.TAG_USER_COMMENT, "focal length:"+String.valueOf(focalLength)+"sensorSize:"+sensorSize);

            // 保存 EXIF 数据
            exifInterface.saveAttributes();
        } catch (IOException e) {
            Log.e(TAG, "Failed to save focal length to EXIF", e);
        }
    }
    @SuppressLint("RestrictedApi")
    private String getSensorSize() {
        if (cameraProvider == null) return "Sensor size not available";

        try {
            // 获取当前绑定的相机信息
            Camera camera = cameraProvider.bindToLifecycle(
                    this,
                    cameraSelector,
                    imageCapture
            );
            CameraInfo cameraInfo = camera.getCameraInfo();

            // 获取所有可用相机信息
            List<CameraInfo> availableCameras = cameraProvider.getAvailableCameraInfos();
            String cameraId = null;

            for (CameraInfo info : availableCameras) {
                if ((isFrontCamera && info.getCameraSelector().getLensFacing() == CameraSelector.LENS_FACING_FRONT) ||
                        (!isFrontCamera && info.getCameraSelector().getLensFacing() == CameraSelector.LENS_FACING_BACK)) {
                    // 使用 CameraManager 获取相机 ID
                    CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
                    for (String id : cameraManager.getCameraIdList()) {
                        CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(id);
                        Integer lensFacing = characteristics.get(CameraCharacteristics.LENS_FACING);
                        if ((isFrontCamera && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_FRONT) ||
                                (!isFrontCamera && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK)) {
                            cameraId = id;
                            break;
                        }
                    }
                    break;
                }
            }

            if (cameraId == null) {
                Log.e(TAG, "Failed to find camera ID");
                return "Failed to find camera ID";
            }

            // 使用 CameraManager 获取传感器大小
            CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
            CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
            SizeF sensorSize = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE);

            if (sensorSize != null) {
                String sensorSizeString = sensorSize.getWidth() + "mm x " + sensorSize.getHeight() + "mm";
                Log.d(TAG, "Sensor size: " + sensorSizeString);
                return sensorSizeString;
            } else {
                Log.w(TAG, "No sensor size available for camera ID: " + cameraId);
                return "No sensor size available";
            }
        } catch (Exception e) {
            Log.e(TAG, "Error getting sensor size", e);
            return "Error getting sensor size";
        }
    }
    @SuppressLint("RestrictedApi")
    private float getFocalLength() {
        if (cameraProvider == null) return 0f;

        try {
            // 获取当前绑定的相机信息
            Camera camera = cameraProvider.bindToLifecycle(
                    this,
                    cameraSelector,
                    imageCapture
            );
            CameraInfo cameraInfo = camera.getCameraInfo();

            // 获取所有可用相机信息
            List<CameraInfo> availableCameras = cameraProvider.getAvailableCameraInfos();
            String cameraId = null;

            for (CameraInfo info : availableCameras) {
                if ((isFrontCamera && info.getCameraSelector().getLensFacing() == CameraSelector.LENS_FACING_FRONT) ||
                        (!isFrontCamera && info.getCameraSelector().getLensFacing() == CameraSelector.LENS_FACING_BACK)) {
                    // 使用 CameraManager 获取相机 ID
                    CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
                    for (String id : cameraManager.getCameraIdList()) {
                        CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(id);
                        Integer lensFacing = characteristics.get(CameraCharacteristics.LENS_FACING);
                        if ((isFrontCamera && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_FRONT) ||
                                (!isFrontCamera && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK)) {
                            cameraId = id;
                            break;
                        }
                    }
                    break;
                }
            }

            if (cameraId == null) {
                Log.e(TAG, "Failed to find camera ID");
                return 0f;
            }

            // 使用 CameraManager 获取焦距信息
            CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
            CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
            float[] focalLengths = characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS);

            if (focalLengths != null && focalLengths.length > 0) {
                return focalLengths[0]; // 返回第一个可用焦距
            } else {
                Log.w(TAG, "No focal lengths available for camera ID: " + cameraId);
                return 0f;
            }
        } catch (Exception e) {
            Log.e(TAG, "Error getting focal length", e);
            return 0f;
        }
    }



    private void compressImage(File file) {
        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
        try (FileOutputStream fos = new FileOutputStream(file)) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setupPinchToZoom() {
        scaleGestureDetector = new ScaleGestureDetector(this, new ScaleGestureDetector.SimpleOnScaleGestureListener() {
            @Override
            public boolean onScale(ScaleGestureDetector detector) {
                if (cameraControl != null && cameraInfo != null) {
                    float currentZoomRatio = cameraInfo.getZoomState().getValue().getZoomRatio();
                    float delta = detector.getScaleFactor();
                    float newZoomRatio = currentZoomRatio * delta;

                    // 限制缩放范围
                    float minZoom = cameraInfo.getZoomState().getValue().getMinZoomRatio();
                    float maxZoom = cameraInfo.getZoomState().getValue().getMaxZoomRatio();
                    newZoomRatio = Math.max(minZoom, Math.min(newZoomRatio, maxZoom));

                    cameraControl.setZoomRatio(newZoomRatio);
                }
                return true;
            }
        });

        pvCameraPreview.setOnTouchListener((view, motionEvent) -> {
            scaleGestureDetector.onTouchEvent(motionEvent);
            return true;
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            usbReaderTool.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        usbReaderTool.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        usbReaderTool.onDestroy();
    }
}